<?php
/**
 * @Notes:【】
 * @User: zwc
 * @Date: 2022-05-01 20:47
 */

namespace App\Repository\WebSocket;

use App\Model\Admin\Admin;
use Firebase\JWT\JWT;
use Hyperf\WebSocketServer\Context;

class UsersData
{
    protected $uid = 0;

    protected $type = 0;

    protected $token = '';

    protected $from = '';

    public function instance($token, $data, $from)
    {
        $this->token = $token;
        $this->from = $from;
        if ($data instanceof \Hyperf\HttpMessage\Uri\Uri) {
            $this->uri($data, $from);
        }
        return $this;
    }

    public function toArray()
    {
        return [
            'uid' => $this->uid,
            'type' => $this->type,
        ];
    }

    public function toJson()
    {
        return json_encode($this->toArray());
    }

    public function uri(\Hyperf\HttpMessage\Uri\Uri $data, $from)
    {
        switch ($data->getPath()) {
            case '/':
                $User = new Admin();
                $this->uid = $User->check_token($this->token);
                $this->type = 0;
                break;
            case '/user':
                $token = trim(ltrim($this->token));
//                dump($token);
                list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
                $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
                $uid = $payload->jti->id;
                $this->uid = $uid;
                if ($from == 'game') {
                    $this->type = 2;
                } else {
                    $this->type = 1;
                }
                break;
        }
    }

    /**
     * @Notes:【】
     * @User: zwc
     * @Date: 2022-05-01 21:19
     * @return self
     */
    public static function get()
    {
        $userData = Context::get('userData');
        return $userData;
    }

    /**
     * @return int
     */
    public function getUid(): int
    {
        return $this->uid;
    }

    /**
     * @return int
     */
    public function getType(): int
    {
        return $this->type;
    }

    /**
     * @return string
     */
    public function getFrom(): string
    {
        return $this->from;
    }
}